package com.hubu.controller;

import com.github.pagehelper.PageInfo;
import com.hubu.pojo.Commodity;
import com.hubu.service.CommodityService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Controller
@RequestMapping("/commodity")
public class CommodityController {

    @Resource
    private CommodityService commodityService;

    @PostMapping("/add")
    public String addCommodity(Model model, Commodity commodity) {
        int i = commodityService.addCommodity(commodity);
        return "redirect:/commodity";
    }

    @GetMapping()
    public String getCommodities(Model model, @RequestParam(defaultValue = "") String name, @RequestParam(defaultValue = "1") int pageNum) {
        PageInfo<Commodity> commodities = commodityService.getCommodities(name, pageNum);
        model.addAttribute("commodities", commodities);
        return "/home";
    }

    @GetMapping("/delete")
    public String deleteComById(@Param("id") Long id) {
        commodityService.deleteComById(id);
        return "redirect:/commodity";
    }

    @GetMapping("/edit")
    public String editComById(Model model, Long id) {
        Commodity commodity = commodityService.getCommodityById(id);
        model.addAttribute("commodity", commodity);
        return "edit";
    }
}
